export class MessageHandler {
  constructor(app) {
    this.app = app;
    this.unreadCount = 0;
  }

  handleMessage(data) {
    if (!this.app.nickname && data.type !== 'system' && data.type !== 'setClientId') {
      return;
    }

    switch (data.type) {
      case 'message':
        this.addMessage(data);
        break;
      case 'image':
        this.addImageMessage(data);
        break;
      case 'file':
        this.addFileMessage(data);
        break;
      case 'video':
        this.addVideoMessage(data);
        break;
      case 'userList':
        this.updateUserList(data.users);
        break;
      case 'system':
        this.addSystemMessage(data.message);
        break;
      case 'setClientId':
        this.app.setClientId(data.clientId);
        break;
      case 'fileSaved':
        this.handleFileSaved();
        break;
    }

    this.updateUnreadCount();
  }

  addMessage(data) {
    const messageElement = document.createElement('div');
    messageElement.classList.add('message');
    messageElement.classList.add(data.clientId === this.app.clientId ? 'current-user' : 'other-user');

    const header = document.createElement('div');
    header.classList.add('message-header');
    header.innerHTML = `
      <span>${data.nickname}</span>
      <span>${new Date(data.timestamp).toLocaleTimeString()}</span>
    `;

    const content = document.createElement('div');
    content.classList.add('message-content');
    content.textContent = data.message;

    messageElement.appendChild(header);
    messageElement.appendChild(content);
    this.app.domManager.elements.messages.appendChild(messageElement);
    this.app.domManager.scrollToBottom();
  }

  addImageMessage(data) {
    const messageElement = document.createElement('div');
    messageElement.classList.add('message');
    messageElement.classList.add(data.clientId === this.app.clientId ? 'current-user' : 'other-user');

    const header = document.createElement('div');
    header.classList.add('message-header');
    header.innerHTML = `
      <span>${data.nickname}</span>
      <span>${new Date(data.timestamp).toLocaleTimeString()}</span>
    `;

    const content = document.createElement('div');
    content.classList.add('message-content');

    const imgContainer = document.createElement('div');
    imgContainer.classList.add('image-container');

    const img = document.createElement('img');
    img.src = data.url;
    img.alt = data.filename;
    img.classList.add('message-image');
    img.addEventListener('click', () => this.openImageModal(data.url));

    imgContainer.appendChild(img);
    content.appendChild(imgContainer);
    messageElement.appendChild(header);
    messageElement.appendChild(content);
    this.app.domManager.elements.messages.appendChild(messageElement);
    this.app.domManager.scrollToBottom();
  }

  addFileMessage(data) {
    const messageElement = document.createElement('div');
    messageElement.classList.add('message');
    messageElement.classList.add(data.clientId === this.app.clientId ? 'current-user' : 'other-user');

    const header = document.createElement('div');
    header.classList.add('message-header');
    header.innerHTML = `
      <span>${data.nickname}</span>
      <span>${new Date(data.timestamp).toLocaleTimeString()}</span>
    `;

    const content = document.createElement('div');
    content.classList.add('message-content');

    const fileContainer = document.createElement('div');
    fileContainer.classList.add('file-container');

    const link = document.createElement('a');
    link.href = data.url;
    link.download = data.filename;
    link.textContent = data.filename;
    link.classList.add('file-link');

    const size = document.createElement('span');
    size.classList.add('file-size');
    size.textContent = ` (${this.app.fileHandler.formatFileSize(data.size)})`;

    fileContainer.appendChild(link);
    fileContainer.appendChild(size);
    content.appendChild(fileContainer);
    messageElement.appendChild(header);
    messageElement.appendChild(content);
    this.app.domManager.elements.messages.appendChild(messageElement);
    this.app.domManager.scrollToBottom();
  }

  addVideoMessage(data) {
    const messageElement = document.createElement('div');
    messageElement.classList.add('message');
    messageElement.classList.add(data.clientId === this.app.clientId ? 'current-user' : 'other-user');

    const header = document.createElement('div');
    header.classList.add('message-header');
    header.innerHTML = `
      <span>${data.nickname}</span>
      <span>${new Date(data.timestamp).toLocaleTimeString()}</span>
    `;

    const content = document.createElement('div');
    content.classList.add('message-content');

    const videoContainer = document.createElement('div');
    videoContainer.classList.add('video-container');

    const videoPreview = document.createElement('div');
    videoPreview.classList.add('video-preview');

    if (data.thumbnail) {
      videoPreview.style.backgroundImage = `url(${data.thumbnail})`;
    } else {
      videoPreview.classList.add('default-video-preview');
    }

    const playButton = document.createElement('div');
    playButton.classList.add('play-button');
    playButton.innerHTML = `
      <svg viewBox="0 0 24 24">
        <path fill="currentColor" d="M8 5v14l11-7z"/>
      </svg>
    `;

    videoPreview.addEventListener('click', () => this.openVideoModal(data));
    videoPreview.appendChild(playButton);
    videoContainer.appendChild(videoPreview);

    const fileInfo = document.createElement('div');
    fileInfo.classList.add('file-info');
    fileInfo.innerHTML = `
      <a href="${data.url}" download="${data.filename}" class="file-link">${data.filename}</a>
      <span class="file-size">(${this.app.fileHandler.formatFileSize(data.size)})</span>
    `;

    content.appendChild(videoContainer);
    content.appendChild(fileInfo);
    messageElement.appendChild(header);
    messageElement.appendChild(content);
    this.app.domManager.elements.messages.appendChild(messageElement);
    this.app.domManager.scrollToBottom();
  }

  addSystemMessage(message) {
    const systemMessage = document.createElement('div');
    systemMessage.classList.add('system-message');
    systemMessage.textContent = message;
    this.app.domManager.elements.messages.appendChild(systemMessage);
    this.app.domManager.scrollToBottom();
  }

  updateUserList(users) {
    const userList = this.app.domManager.elements.userList;
    userList.innerHTML = '';
    users.forEach(user => {
      const li = document.createElement('li');
      li.textContent = user;
      userList.appendChild(li);
    });
  }

  handleFileSaved() {
    setTimeout(() => {
      this.app.domManager.hideProgress();
    }, 500);
    this.app.domManager.elements.fileInput.value = '';
  }

  openImageModal(imageUrl) {
    const modal = document.createElement('div');
    modal.classList.add('image-modal');

    const img = document.createElement('img');
    img.src = imageUrl;
    img.classList.add('modal-image');

    modal.appendChild(img);
    document.body.appendChild(modal);

    modal.addEventListener('click', () => {
      document.body.removeChild(modal);
    });
  }

  openVideoModal(data) {
    const video = document.createElement('video');
    video.src = data.url;
    video.controls = true;

    const modal = document.createElement('div');
    modal.classList.add('video-modal');
    modal.appendChild(video);

    modal.addEventListener('click', (e) => {
      if (e.target === modal) {
        document.body.removeChild(modal);
      }
    });

    document.body.appendChild(modal);
    video.play();
  }

  updateUnreadCount() {
    if (!document.hasFocus()) {
      this.unreadCount++;
      document.title = `(${this.unreadCount}) 局域网聊天室`;
    }
  }

  resetUnreadCount() {
    this.unreadCount = 0;
    document.title = '局域网聊天室';
  }
} 